package com.bbzn.device.client.controller;

import com.bbzn.device.client.vo.req.HealthVO;
import com.bbzn.device.client.vo.req.RangeEntity;
import com.bbzn.device.client.aspect.OperationAnnotation;
import com.bbzn.device.client.constant.DeviceConstant;
import com.bbzn.device.client.constant.MongoDbConstant;
import com.bbzn.device.client.dataobject.HealthDataHis;
import com.bbzn.device.client.dataobject.SystemParam;
import com.bbzn.device.client.dto.device.DeviceInfoDTO;
import com.bbzn.device.client.exception.DefinitException;
import com.bbzn.device.client.service.*;
import com.bbzn.device.client.utils.*;
import com.bbzn.device.client.utils.date.DateUtil;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 黄志鹏
 * @Date 2021/3/16 17:11
 * @Version 1.0
 */

@RestController
@RequestMapping("/health")
@Slf4j
@Api(value = "health", tags = "健康管理")
@ApiSort(value = 1)// 大分类顺序
//@CrossOrigin
public class HealthController extends BaseApiService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemParamByCacheService systemParamByCacheService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private SimpleMongoService simpleMongoService;

    @Autowired
    private DeviceProcessService deviceProcessService;


    /**
     * 查询健康数据
     *
     * @param reqVO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getHealthData", method = RequestMethod.POST)
    @OperationAnnotation(content = "查询健康数据")
    public BaseResponse getHealthData(@RequestBody HealthVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getImei()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        DeviceInfoDTO deviceInfo = deviceService.selectByImei(reqVO.getImei());
        return setResultSuccess(deviceInfo);
    }

    /**
     * 查询健康数据列表
     *
     * @param reqVO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getHealthDataList", method = RequestMethod.POST)
    @OperationAnnotation(content = "查询健康数据列表")
    public BaseResponse getHealthDataList(@RequestBody HealthVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        if (!OptionalBean.ofNullable(reqVO.getHealthDataType()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_DATA_TYPE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (reqVO.getPageNum() == null) {
            reqVO.setPageNum(1);
        }
        if (reqVO.getPageSize() == null) {
            reqVO.setPageSize(50);
        }
        List<String> list = deviceProcessService.findByImeisByOperatorId(userId);
        List<String> list2 = deviceService.findByAllImeis(userId);
        list.addAll(list2);
        if (OptionalBean.ofNullable(reqVO.getImei()).isPresent() && !list.contains(reqVO.getImei())) {
            SystemParam systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_IMEI_NOT_EXIST_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        Date startTime = DateUtil.stringToDate(reqVO.getStartDate(),"yyyy-MM-dd HH:mm:ss");
        Date endTime = DateUtil.stringToDate(reqVO.getEndDate(),"yyyy-MM-dd HH:mm:ss");
        Map<String, RangeEntity> range = new HashMap<>();
        if (OptionalBean.ofNullable(reqVO.getStartDate()).isPresent() && OptionalBean.ofNullable(reqVO.getEndDate()).isPresent()) {
            RangeEntity rangeEntity = new RangeEntity();
            rangeEntity.setGte(startTime.getTime());
            rangeEntity.setLt(endTime.getTime());
            range.put("createTime", rangeEntity);
        }

        Map<String, Object> conditions = new HashMap();
        conditions.put("dataType", reqVO.getHealthDataType());

        Map<String, List<String>> inList = new HashMap();
        inList.put("imei", list);

        PageInfo<HealthDataHis> page = simpleMongoService.selectPageByCondition(MongoDbConstant.HEALTH_DATA, range,
                conditions,inList,HealthDataHis.class, reqVO.getPageNum(),reqVO.getPageSize());
        return setResultSuccess(page);
    }
}
